/**
 * 
 */

package net.messagenet.mazor.web.mngbeans;
import java.io.Serializable;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.PostConstruct;
import javax.faces.model.SelectItem;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import net.messagenet.mazor.DO.CustomerDO;
import net.messagenet.mazor.DO.DpaDO;
import net.messagenet.mazor.DO.DpaProductDO;
import net.messagenet.mazor.DO.ProductDO;
import net.messagenet.mazor.ejb.facade.MZRFacadeLocal;
import net.messagenet.mazor.exception.MZRApplicativeException;
import net.messagenet.mazor.exception.MZRInternalServerException;
import net.messagenet.mazor.infra.cache.UserCacheManager;

import org.ajax4jsf.model.KeepAlive;
import org.apache.log4j.Logger;
import org.hibernate.validator.Email;
import org.hibernate.validator.NotEmpty;
import org.hibernate.validator.Pattern;

/**
 * @author Idan
 *
 */
@KeepAlive
public class NewDPARequestManagedBean implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -5388230760485952510L;

	
	private List<DpaProductDO> productList;
	private UserCacheManager cacheManager;
	private MZRFacadeLocal facade=null;

	

	private Logger logger = Logger.getLogger(this.getClass());
	
	private int dpaId;
	private Date requestDate;
	private int selectedDpaIdFormTable;
	
	@Email
    @NotEmpty
	private String email;
	
	@Pattern(regex="((\\w+@\\w+\\.\\w+)+(,\\w+@\\w+\\.\\w+)*)|", message="Not a valid CC field")
	private String cc;
	private String distrib_name;
	private String contact;
	private String dialogic_fse;
	private String customer_name;
	private int customer_id;

	private String customer_location;
	private String end_user_name;
	private String reason_req;
	private String info;
	
	private String Dialogic_Item ;
	private String Product_Name;
	private int product_id;

	private double SDC;
	private double Traget_Cost;
	private String Competitor;
	private double Competitors_Price;
	private int Qty;
	private double approvedPrice;
	private Date expDate;

	private List<DpaDO> drafts;
	private List<SelectItem > draftsLabel;
	
	private String selectedDraft;


	private int removePrdIdx;
	private List<DpaProductDO> removePrds;
	private Map<Integer,DpaDO> olddpasMap;
	private List<DpaDO> olddpas;
	
	@PostConstruct
	public void init() {
		
		InitialContext ic;
			
		try {
				ic = new InitialContext();
				facade = (MZRFacadeLocal) ic.lookup("MZRFacade/local");
			} catch (NamingException e) {
				logger.error(e.getMessage(),e);
			}
			logger.debug("loadding cusomter cache");
			
			try {
				cacheManager = facade.getUserCacheManager();
			} catch (MZRInternalServerException e) {
				logger.error(e.getMessage(), e);
			}
			productList= new LinkedList<DpaProductDO>();
			
			logger.debug("getting drafts");
			
			try {
				drafts = facade.getDPADrafts();
			} catch (MZRInternalServerException e) {
				logger.error(e.getMessage(), e);
			} 
			productList= new LinkedList<DpaProductDO>();
			
			try {
				 olddpasMap = facade.getAllDPAs();
			} catch (MZRInternalServerException e) {
				logger.error(e.getMessage(), e);
			}
			
			olddpas= new LinkedList<DpaDO>();
			for ( Entry<Integer, DpaDO> e : olddpasMap.entrySet()) {
				olddpas.add(e.getValue());
			}
			
			draftsLabel = new LinkedList<SelectItem>();
			for (DpaDO dpaDo : drafts) {
				draftsLabel.add(new SelectItem(String.valueOf(dpaDo.getFileName())));
			}
			
			removePrds = new LinkedList<DpaProductDO>();
			
	   }
	/**
	 * This method is called from the JSF when the users adds a new proudct to the lists 
	 * of product 
	 * 
	 */
	public void add(){
		DpaProductDO c = new DpaProductDO();
		ProductDO prd = new ProductDO();
		prd.setDialogicItemKey(Dialogic_Item);
		prd.setId(product_id);
		prd.setProductName(Product_Name);
		c.setCompetitor(Competitor);
		c.setCompetitorsPrice(Competitors_Price);

		c.setQuantity(Qty);
		c.setSdc(SDC);
		c.setTargetCost(Traget_Cost);
		c.setApprovedPrice(approvedPrice);
		c.setProduct(prd);
		productList.add(c);
		cleanProductFields();
		
	}
	/**
	 *  This method clears the fields of the product
	 * 
	 */
	private void cleanProductFields(){
		Competitor="";
		Competitors_Price=0;
		Dialogic_Item="";
		Product_Name="";
		Qty=0;
		SDC=0;
		Traget_Cost=0;
		approvedPrice=0;
	}
	/**
	 * 
	 * This method builds a DPA DO from the data in the bean. ready to be
	 * saved in the system
	 * 
	 * @return DPADO
	 */
	private DpaDO buildDpaDo(){
		DpaDO dpa = new DpaDO();
		dpa.setId(dpaId);
		dpa.setAdditionalInformation(info);
		dpa.setContact(contact);
		dpa.setDialogicfse(dialogic_fse);
		dpa.setEmail(email);
		if (!cc.equals(""))
			dpa.setCc(cc);
		else
			dpa.setCc(null);
		dpa.setEndUserName(end_user_name);
		dpa.setRequestDate(requestDate);
		dpa.setReasonForRequest(reason_req);
		
		//cusomter
		CustomerDO c = new CustomerDO();
		c.setName(customer_name);
		c.setId(customer_id);
		c.setLocation(customer_location);
		dpa.setCustomer(c);
		
		dpa.setDpaProducts(productList);
		dpa.updateFileName();
		return dpa;
	}
	/**
	 * 
	 * This method is called by JSF when the user wants to save the DPA request
	 * 
	 * @return a paged to be directed to
	 */
	public String createRequest(){

		logger.debug("create new DPA request");
		try {
			facade.createDPARequest( buildDpaDo());
			
		}catch (MZRInternalServerException e) {
			logger.error(e.getMessage(), e);
			return "opr/failedopr.jsp";
		} catch (MZRApplicativeException e) {
			logger.error(e.getMessage(), e);
			return "opr/failedopr.jsp";
		}

		removeOldPrds();
		return "opr/successnewfilereq.jsp";
		
	}
	
	/**
	 * This method is called when the user chose to remove proudest form the dpa draft
	 * is removes those products form the system
	 * 
	 * 
	 */
	private void removeOldPrds() {
		if (removePrds.size()!=0){
			logger.debug("deleting old produtcs");
			try {
				facade.removeDPAProducts( removePrds);
				
			}catch (MZRInternalServerException e) {
				logger.error(e.getMessage(), e);
			}
		}
		
	}
	/**
	 * 
	 * This method is called by JSF when the user wants to save the DPA request as draft
	 * 
	 * @return a paged to be directed to
	 */
	public String createDraft(){
		
		logger.debug("saving DPA as fraft");
		try {
			facade.saveDPADraft( buildDpaDo());
			
		}catch (MZRInternalServerException e) {
			logger.error(e.getMessage(), e);
			return "opr/failedopr.jsp";
		} catch (MZRApplicativeException e) {
			logger.error(e.getMessage(), e);
			return "opr/failedopr.jsp";
		}
		removeOldPrds();
		return "opr/successdraft.jsp";
	}
	
	/**
	 * This method is called when the user wants to fill the page with data from a draft
	 * it has selected
	 * 
	 */
	
	public void loadDraft(){
		//find selected draft
		DpaDO draft =null;
		for (DpaDO d : drafts) {
			if (selectedDraft.equals(String.valueOf(d.getFileName())))
				draft=d;
		}
		dpaId= draft.getId();
		setInfo(draft.getAdditionalInformation());
		setContact(draft.getContact());
		setRequestDate(draft.getRequestDate());
		setDialogic_fse(draft.getDialogicfse());
		setEmail(draft.getEmail());
		setCc(draft.getCc());
		setEnd_user_name(draft.getEndUserName());
		setReason_req(draft.getReasonForRequest());
		
		if (draft.getCustomer()!=null){
			setCustomer_id(draft.getCustomer().getId());
			setCustomer_location(draft.getCustomer().getLocation());
			setCustomer_name(draft.getCustomer().getName());
		}
		productList = draft.getDpaProducts();
		
		
	}
	/**
	 * This method is called when the remove proudct is pushed.
	 * if this product was in saved in the system. it is added to a list that will 
	 * be removed later
	 * 
	 */
	public void removePrd(){
		DpaProductDO prd = productList.get(removePrdIdx);
		productList.remove(removePrdIdx);
		if (prd.getId()!=0){
			removePrds.add(prd);
		}
		
	}
	/**
	 * This method is called by ajax from autocomplete
	 * 
	 * @param suggest prefix
	 * @return
	 */
    public List<CustomerDO> autoCompleteCustomer(Object suggest){    	
    	List<CustomerDO> result = cacheManager.getCustomersWithPrefix((String)suggest);
    	return result;
    }
	/**
	 * This method is called by ajax from autocomplete
	 * 
	 * @param suggest prefix
	 * @return
	 */
    public List<ProductDO> autoCompleteProducts(Object suggest){    	
    	List<ProductDO> result = cacheManager.getProductsWithPrefix((String)suggest);
    	return result;
    }
    

    public void selectDpaFromTable(){
    	DpaDO dpaselcted = olddpasMap.get(selectedDpaIdFormTable);
    	
    	dpaId=0;
    	info=dpaselcted.getAdditionalInformation();
		contact= dpaselcted.getContact();
		contact =dpaselcted.getContact();
		dialogic_fse = dpaselcted.getDialogicfse();
		
		email=dpaselcted.getEmail();
		cc=dpaselcted.getCc();
		end_user_name=dpaselcted.getEndUserName();
		reason_req = dpaselcted.getReasonForRequest();
		
		customer_id= dpaselcted.getCustomer().getId();
		customer_name = dpaselcted.getCustomer().getName();
		customer_location= dpaselcted.getCustomer().getLocation();
		expDate= dpaselcted.getExpirationDate();
		
		productList = dpaselcted.getDpaProducts();
		
		
    	
    }
	public double getApprovedPrice() {
		return approvedPrice;
	}

	public void setApprovedPrice(double approvedPrice) {
		this.approvedPrice = approvedPrice;
	}

	
	public int getProduct_id() {
		return product_id;
	}

	public void setProduct_id(int product_id) {
		this.product_id = product_id;
	}

	public String getDialogic_Item() {
		return Dialogic_Item;
	}

	public void setDialogic_Item(String dialogic_Item) {
		Dialogic_Item = dialogic_Item;
	}

	public String getProduct_Name() {
		return Product_Name;
	}

	public void setProduct_Name(String product_Name) {
		Product_Name = product_Name;
	}

	public double getSDC() {
		return SDC;
	}

	public void setSDC(double sDC) {
		SDC = sDC;
	}

	public double getTraget_Cost() {
		return Traget_Cost;
	}

	public void setTraget_Cost(double traget_Cost) {
		Traget_Cost = traget_Cost;
	}

	public String getCompetitor() {
		return Competitor;
	}

	public void setCompetitor(String competitor) {
		Competitor = competitor;
	}

	public double getCompetitors_Price() {
		return Competitors_Price;
	}

	public void setCompetitors_Price(double competitors_Price) {
		Competitors_Price = competitors_Price;
	}

	public int getQty() {
		return Qty;
	}

	public void setQty(int qty) {
		Qty = qty;
	}


	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getCc() {
		return cc;
	}

	public void setCc(String cc) {
		this.cc = cc;
	}

	public List<DpaProductDO> getProductList() {
		return productList;
	}


	public void setDrafts(List<DpaDO> drafts) {
		this.drafts = drafts;
	}

	public List<DpaDO> getDrafts() {
		return drafts;
	}

	public List<SelectItem> getDraftsLabel() {
		return draftsLabel;
	}

	public void setDraftsLabel(List<SelectItem> draftsLabel) {
		this.draftsLabel = draftsLabel;
	}

	public void setSelectedDraft(String selectedDraft) {
		this.selectedDraft = selectedDraft;
	}

	public String getSelectedDraft() {
		return selectedDraft;
	}

	public Date getRequestDate() {
		return requestDate;
	}

	public void setRequestDate(Date requestDate) {
		this.requestDate = requestDate;
	}

	public void setDistrib_name(String distrib_name) {
		this.distrib_name = distrib_name;
	}

	public String getDistrib_name() {
		return distrib_name;
	}

	public void setContact(String contact) {
		this.contact = contact;
	}

	public String getContact() {
		return contact;
	}

	public void setDialogic_fse(String dialogic_fse) {
		this.dialogic_fse = dialogic_fse;
	}

	public String getDialogic_fse() {
		return dialogic_fse;
	}

	public void setCustomer_location(String customer_location) {
		this.customer_location = customer_location;
	}

	public String getCustomer_location() {
		return customer_location;
	}

	public void setCustomer_name(String customer_name) {
		this.customer_name = customer_name;
		
	}

	public String getCustomer_name() {
		return customer_name;
	}

	public void setEnd_user_name(String end_user_name) {
		this.end_user_name = end_user_name;
	}

	public String getEnd_user_name() {
		return end_user_name;
	}

	public void setExpDate(Date expDate) {
		this.expDate = expDate;
	}
	public Date getExpDate() {
		return expDate;
	}
	public void setOlddpas(List<DpaDO> olddpas) {
		this.olddpas = olddpas;
	}
	public List<DpaDO> getOlddpas() {
		return olddpas;
	}
	public void setSelectedDpaIdFormTable(int selectedDpaIdFormTable) {
		this.selectedDpaIdFormTable = selectedDpaIdFormTable;
	}
	public int getSelectedDpaIdFormTable() {
		return selectedDpaIdFormTable;
	}
	public void setReason_req(String reason_req) {
		this.reason_req = reason_req;
	}

	public String getReason_req() {
		return reason_req;
	}

	public int getRemovePrdIdx() {
		return removePrdIdx;
	}

	public void setRemovePrdIdx(int removePrdIdx) {
		this.removePrdIdx = removePrdIdx;
	}

	public void setInfo(String info) {
		this.info = info;
	}

	public String getInfo() {
		return info;
	}
	public int getCustomer_id() {
		return customer_id;
	}

	public void setCustomer_id(int customer_id) {
		this.customer_id = customer_id;
	}



}
